
import * as path from "path";
import * as child_process from "child_process";

import { info } from "./lib/info";

export default function stop() {
    let consulShell = "";
    let nginxShell = "";
    let consulTemplateShell = "";
    if (info.system === "windows") {
        consulShell = "taskkill /f /im consul.exe";
        consulTemplateShell = "taskkill /f /im consul-template.exe";
        nginxShell = "taskkill /f /im nginx.exe";
    } else {
        consulShell = `kill -9 \`cat ${ path.resolve(__dirname, "../") }/consul/consul.pid\``;
        consulTemplateShell = `kill -9 \`cat ${ path.resolve(__dirname, "../") }/consul-template/consul-template.pid\``;

        const nginxDir = path.resolve(__dirname, "../nginx");
        const nginxBin = path.resolve(nginxDir, "sbin/nginx");
        let nginxConfig = path.resolve(nginxDir, "conf/nginx.conf");
        nginxShell = `${ nginxBin } -p ${ nginxDir } -c ${ nginxConfig } -s stop`;
    }
    return Promise.all([
        new Promise((resolve) => {
            console.log(consulTemplateShell);
            child_process.exec(consulTemplateShell, function (error) {
                if (error) {
                    console.log("consul-template stop error!");
                }
                else {
                    console.log("consul-template stoped!");
                }
                resolve();
            });
        }),
        new Promise((resolve) => {
            console.log(consulShell);
            child_process.exec(consulShell,  { encoding: 'utf8' }, function (error) {
                if (error) {
                    console.log("consul stop error!");
                }
                else {
                    console.log("consul stoped!");
                }
                resolve();
            });
        }),
        new Promise((resolve) => {
            console.log(nginxShell);
            child_process.exec(nginxShell, function (error) {
                if (error) {
                    console.log("nginx stop error!");
                }
                else {
                    console.log("nginx stoped!");
                }
                resolve();
            });
        }),
    ]);
};
